import React, { PureComponent } from 'react';
import { Table, Button, Icon } from 'antd';
import { connect } from 'dva';
import CrossSectionBase from "../../components/forms/crossSectionBase"
import "../structure/index.less"
import "../../Common.less"
import ToolConfigModals from '../../components/toolConfigModals';
import { worker } from "../../utils/worker"
import {cloneDeep} from "lodash"
import { bus } from "../../utils/bus"
class CrossSectionDetail extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            cindex1: 0,
            cindex2: 0,
            showBg: false,
            otype: null,
            mode: "",
            detail: {},
            tloading: false,
            loading: true,
            crossSectionTemplateAttrs: [],
            crossSectionTemplateGeoAttrs: []

        }
        this.editProp = this.editProp.bind(this)
        this.getFormData = this.getFormData.bind(this)
        this.submit = this.submit.bind(this)
        this.getData = this.getData.bind(this)
        this.addGeoAttrs = this.addGeoAttrs.bind(this)
        this.removeProp=this.removeProp.bind(this)
    }
    async editProp(e, item, type, index) {
        e.preventDefault()

        if (type == 1) {
            this.setState({
                otype: 1,
                cindex1: index
            })
        } else {
            this.setState({
                otype: 2,
                cindex2: index
            })
        }
        this.state.modalContext.updateModal({
            visible: true,
            title: "修改属性",
            width:"800px",
            event: { code: 'crossSectionProp' },
            extra: {
                mode: "edit",
                propData: item,
            }
        });
    }
    removeProp(e, item, type, index){
        let { crossSectionTemplateGeoAttrs } = this.state;
        crossSectionTemplateGeoAttrs.splice(index,1)
        this.setState({
            crossSectionTemplateGeoAttrs:[...crossSectionTemplateGeoAttrs]
        })
    }
    getFormData(data) {
        if (data) {
            this.setState({
                crossSectionTemplateAttrs: data.crossSectionTemplateAttrs, crossSectionTemplateGeoAttrs: data.crossSectionTemplateGeoAttrs, uploadFileInfo: data.uploadFileInfo, dirName: data.dirName
            })
        }

    }
    componentWillUnmount() {
        bus.off("crossSectionPropFinsh")
        bus.off("crossSectionPropFinsh2")
    }
    async componentDidMount() {
        const { dictlist } = this.props
        let a = this.props.match.params
        let id = a.id;
        if (a.mode == "overview") {
            await this.setState({
                mode: a.mode,
                showBg: true
            })
        } else {
            await this.setState({
                mode: a.mode,
            })
        }


        bus.on("crossSectionPropFinsh", res => {
            let { mode, crossSectionTemplateGeoAttrs } = this.state;
            crossSectionTemplateGeoAttrs.push(res)
            this.setState({
                crossSectionTemplateGeoAttrs: [...crossSectionTemplateGeoAttrs]
            })
        })
        bus.on("crossSectionPropFinsh2", res => {
            let { mode, crossSectionTemplateAttrs, crossSectionTemplateGeoAttrs, otype, cindex1, cindex2 } = this.state;
            if (otype == 1) {
                Object.assign(crossSectionTemplateAttrs[cindex1], res)
                crossSectionTemplateAttrs.splice(cindex1, 1, crossSectionTemplateAttrs[cindex1])
            } else {
                Object.assign(crossSectionTemplateGeoAttrs[cindex2], res)
                crossSectionTemplateGeoAttrs.splice(cindex2, 1, crossSectionTemplateGeoAttrs[cindex2])
            }

            this.setState({
                crossSectionTemplateAttrs: [...crossSectionTemplateAttrs], crossSectionTemplateGeoAttrs: [...crossSectionTemplateGeoAttrs]
            })
        })
        let res = await this.props.crossSectionTree()
        let resc = cloneDeep(await worker.loopTreeNode2(res))
        if (resc) {
            this.setState({
                expandedKeys: resc.map(item => item.key),
                treeData: resc
            })
        }

        await this.setState({
            isShowList: dictlist.filter(item => item.dictType == "is_show"),
            isEffectiveList: dictlist.filter(item => item.dictType == "is_effective"),
            isRequiredList: dictlist.filter(item => item.dictType == "is_required"),
            propertyTypeList: dictlist.filter(item => item.dictType == "property_type"),
            unitList: dictlist.filter(item => item.dictType == "unit"),
            isCalculateList: dictlist.filter(item => item.dictType == "is_calculate"),

        })

        if (a.mode != "add") {
            await this.getData(id)
        }
        let context = this.state.context;
        context.updateFormData({ definitionTreeId: a.definitionTreeId && a.definitionTreeId != '-1' ? a.definitionTreeId : "" })
        this.setState({
            loading: false
        })
    }

    async getData(id) {
        this.setState({
            tloading: true
        })
        let detail;
        let res = await this.props.crossSectionTemplateDetail({ id })
        const { crossSectionTemplateGeoAttrs, crossSectionTemplateAttrs, uploadFileInfo, dirName } = res;
        detail = res;
        uploadFileInfo.uid = uploadFileInfo.id;
        uploadFileInfo.name = uploadFileInfo.uploadFileName;
        uploadFileInfo.status = 'done';
        uploadFileInfo.url = "http://27.17.20.242:8064/fsds/" + uploadFileInfo.uploadFilePath;
        detail.crossSectionTemplateAttrs = crossSectionTemplateAttrs
        detail.crossSectionTemplateGeoAttrs = crossSectionTemplateGeoAttrs
        detail.uploadFileInfo = uploadFileInfo
        let context = this.state.context;
        context.updateFormData(detail)

        this.setState({
            crossSectionTemplateAttrs,
            crossSectionTemplateGeoAttrs,
            uploadFileInfo: uploadFileInfo,
            dirName,
            detail,
            tloading: false
        })
    }
    async submit(e) {
        const { mode } = this.state;
        e.preventDefault();
        this.setState({
            loading: true
        })
        const { crossSectionTemplateAttrs, crossSectionTemplateGeoAttrs } = this.state;

        let context = this.state.context;
        
        context.getFormValues().then(res => {
            let formdata = new FormData();
            formdata.append(`files`, res.file)
            if (mode == 'add') {

                this.props.addFiles(formdata, fres => {
                    res.crossSectionTemplateAttrs = crossSectionTemplateAttrs;
                    res.crossSectionTemplateGeoAttrs = crossSectionTemplateGeoAttrs;
                    res.crossSectionTemplateFileId = fres[0]
                    delete res.file;
                    this.props.addCrossSectionTemplate(res, results => {
                       
                        this.props.history.go(-1)
                    }, err => {
                        
                    })
                }, err => {
                   
                })

            } else {
       
                if(this.state.context.state.fileupdated){
                    this.props.addFiles(formdata, fres => {
                        res.crossSectionTemplateAttrs = crossSectionTemplateAttrs;
                        res.crossSectionTemplateGeoAttrs = crossSectionTemplateGeoAttrs;
                        res.crossSectionTemplateFileId = fres[0]
                        delete res.file;
                        this.props.updateCrossSectionTemplate(res, results => {

                            this.props.history.go(-1)
                        }, err => {
                           
                        })
                    }, err => {
                       
                    })
                }else{
                    res.crossSectionTemplateAttrs = crossSectionTemplateAttrs;
                    res.crossSectionTemplateGeoAttrs = crossSectionTemplateGeoAttrs;
                    delete res.file
                    this.props.updateCrossSectionTemplate(res, results => {
                      
                        this.props.history.go(-1)
                    }, err => {
                        
                    })
                }
               
            }



        }).catch(err => {
            
        })
        this.setState({
            loading: false
        })
    }
    addGeoAttrs() {
        const { modalContext, mode } = this.state;
        modalContext.updateModal({
            visible: true,
            title: "新增属性",
            width: 800,
            event: { code: 'crossSectionProp' },
            extra: {
                
                mode: "add"
            }
        });
    }
    render() {

        const { showBg, loading, tloading, mode, crossSectionTemplateGeoAttrs, detail, propertyTypeList, unitList } = this.state;
        console.log(crossSectionTemplateGeoAttrs)
        const c1 = [{
            title: 'KEY',
            dataIndex: 'keyName',
            key: 'keyName',
            width: "100px",
        },
        {
            title: '属性名称',
            dataIndex: 'name',
            key: 'name',
            width: "100px",
        },
        {
            title: '类型',
            dataIndex: 'attrDataType',
            key: 'attrDataType',
            width: "100px",
            render: text => text ? propertyTypeList.find(item => item.id == text).dictLabel : ""
        },
        {
            title: '默认值',
            dataIndex: 'defaultValue',
            key: 'defaultValue',
            width: "100px",
        },
        {
            title: '单位',
            dataIndex: 'unit',
            key: 'unit',
            width: "80px",
            render: text => text ? unitList.find(item => item.id == text).dictLabel : ""
        },

        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            width: "100px",

        }]
        const columns = mode != 'overview' ? [
            ...c1,
            {
                title: '操作',
                dataIndex: 'operate',
                key: 'operate',
                width: "120px",
                render: (text, record, index) => <span className="operate"> <a onClick={(e) => this.editProp(e, record, 1, index)}><Icon type="edit" /><span>修改参数</span></a><a onClick={(e) => this.removeProp(e, record, 1, index)}><Icon type="delete" /><span>删除参数</span></a></span>
            }
        ] : [...c1];
        const c2 = c1
        const columns2 = mode != 'overview' ? [
            ...c2,
            {
                title: '操作',
                dataIndex: 'operate',
                key: 'operate',
                width: "120px",
                render: (text, record, index) => <span className="operate"><a onClick={(e) => this.editProp(e, record, 2, index)}><Icon type="edit" /><span>修改参数</span></a><a onClick={(e) => this.removeProp(e, record, 1, index)}><Icon type="delete" /><span>删除参数</span></a></span>
            }
        ] : [...c2]
        return (
            <div style={loading ? { opacity: 0 } : { opacity: 1 }} className="CrossSectionDetail">
                <div className="btitle absMiddle"><div><div><div></div>{mode == 'add' ? '新增截面库' : (mode == 'edit' ? '编辑截面库' : '查看截面库')}</div><div><Button onClick={e => {
                    e.preventDefault()
                    this.props.history.go(-1)
                }}>返回</Button></div></div></div>
                <div>
                    <div className="title">基础信息</div>
                    <CrossSectionBase detail={detail} onLoaded={(context) => {
                        this.setState({ context });
                    }} getFormData={this.getFormData} mode={mode} ></CrossSectionBase>
                    <div className="title">属性信息</div>
                    <div className="tableBox">
                        <div className="title between"><div>几何属性</div>
                            <div>{mode != 'overview' ? <Button onClick={this.addGeoAttrs} type="primary" icon="plus">新增</Button> : undefined}</div></div>
                        <Table loading={tloading} rowKey={record => record.id + record.keyName} bordered pagination={false} dataSource={crossSectionTemplateGeoAttrs ? crossSectionTemplateGeoAttrs : []} columns={columns2} />
                        {/* <div className="title">一般属性</div>
                        <Table loading={tloading} rowKey={record => record.id + record.keyName} bordered pagination={false} dataSource={crossSectionTemplateAttrs ? crossSectionTemplateAttrs : []} columns={columns} /> */}
                    </div>
                    <div className={showBg ? 'bgTrans' : 'none'}></div>
                </div>
                {
                    mode != 'overview' ? <div className="strBtnBox">
                        <Button onClick={this.submit} loading={loading} disabled={loading}>提交</Button><Button onClick={e => {
                            e.preventDefault()
                            this.props.history.go(-1)
                        }}>返回</Button>
                    </div> : undefined
                }

                <ToolConfigModals
                    onLoaded={context => {
                        this.setState({ modalContext: context })
                    }}
                    parent={this}
                />
            </div>
        )
    }
}
export default connect(
    ({
        dict: { dictlist }
    }) => ({
        dictlist
    })
    , dispatch => ({
        crossSectionTree: (values) => dispatch({
            type: 'crossSection/crossSectionTree',
            payload: values
        }),
        addCrossSectionTemplate: (values, onSuccess, onError) => dispatch({
            type: 'crossSection/addCrossSectionTemplate',
            payload: {
                values,
                onSuccess,
                onError,

            }
        }),
        addFiles: (values, onSuccess, onError) => dispatch({
            type: 'crossSection/addFiles',
            payload: {
                values,
                onSuccess,
                onError,

            }
        }),
        updateCrossSectionTemplate: (values, onSuccess, onError) => dispatch({
            type: 'crossSection/updateCrossSectionTemplate',
            payload: {
                values,
                onSuccess,
                onError,

            }
        }),
        crossSectionTemplateDetail: (values,) => dispatch({
            type: 'crossSection/crossSectionTemplateDetail',
            payload: values
        }),
    }))(CrossSectionDetail);